package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.client.user.UserFeignClient;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.Contract;
import com.bwie.pojo.ShopParam;
import com.bwie.pojo.User;
import com.bwie.service.ContractService;
import com.bwie.state.AdminOrUserEnum;
import com.bwie.state.ShopStatusEnum;
import com.bwie.utils.R;
import org.apache.commons.lang3.ObjectUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Shop;
import com.bwie.mapper.ShopMapper;
import com.bwie.service.ShopService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @Author: Mikey
 * @Date:  2025/9/9 11:46
 * @Description: 
 **/

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements ShopService{

    @Resource
    private ShopMapper shopMapper;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private ContractService contractService;

    @Override
    public R getShopList(ShopParam shopParam) {
        if(shopParam.getUserId()==null || shopParam.getUserId()==0){
           return R.ERROR(500,"获取登录人身份失败!");
        }
        //定义一个空集合存放数据
        List<Shop> shops=null;
        User isUser = userFeignClient.getUserById(shopParam.getUserId());

        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(shopParam.getShopName())){
            //商铺名称模糊查询
            queryWrapper.like(Shop::getShopName,shopParam.getShopName());
        }

        if(ObjectUtils.isNotEmpty(shopParam.getStartTime()) && ObjectUtils.isNotEmpty(shopParam.getEndTime())){
            //商铺录入时间区间查询
            queryWrapper.between(Shop::getShopEntryTime,shopParam.getStartTime(),shopParam.getEndTime());
        }

        //首先判断是否是管理员
        if(isUser.getIsAdmin().equals(AdminOrUserEnum.ADMIN.getCode())){
            //是管理员 查询所有
            shops = shopMapper.selectList(queryWrapper);
            shops.stream().forEach(shop -> {
                //负责人名称
                User user = userFeignClient.getUserById(shop.getUserId());
                shop.setUsername(user.getUsername());
                //合同数量  动态计算
                int count = contractService.count(new LambdaQueryWrapper<Contract>().eq(Contract::getShopId, shop.getId()));
                shop.setContractCount(count);
            });
        }else{
            //不是管理员就是普通用户只查自己旗下商铺
            shops = shopMapper.selectList(queryWrapper.eq(Shop::getUserId, shopParam.getUserId()));
            //遍历赋值
            shops.stream().forEach(shop -> {
                User user = userFeignClient.getUserById(shop.getUserId());
                shop.setUsername(user.getUsername());
                //合同数量  动态计算
                int count = contractService.count(new LambdaQueryWrapper<Contract>().eq(Contract::getShopId, shop.getId()));
                shop.setContractCount(count);
            });
        }


        return R.OK(shops);
    }

    @Override
    public R saveShop(Shop shop) {
        //默认新添加提交保障金是店铺状态为续约待审核
        shop.setShopStatus(ShopStatusEnum.PENDING.getCode());
        //进行添加
        shopMapper.insert(shop);
        return R.OK();
    }

    @Override
    public R reContract(Integer id) {
        //先查询
        Shop shop = shopMapper.selectById(id);
        shop.setShopStatus(ShopStatusEnum.PENDING.getCode());
        shopMapper.updateById(shop);
        return R.OK();
    }


    @PostConstruct
    public void SaveRedis(){
        List<Shop> shops = shopMapper.selectList(null);
        //使用消息队列存入redis缓存中
        kafkaTemplate.send("send-msg", JSON.toJSONString(shops));
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @KafkaListener(topics = "send-msg")
    public void sendMsg(String msg, Acknowledgment acknowledgment){
        //存入redis中
        redisTemplate.opsForValue().set("shopManger:shopList",msg,30, TimeUnit.MINUTES);
        //设置手动提交
        acknowledgment.acknowledge();
    }
}
